package metrics

import (
	"fmt"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"net/http"
)

const metricsHTTPPort = 9999

var (
	// ClientConnected 的类型为 prometheus.Gauge, Gauge 是对一个数值的即时测量值，它反映一个值的瞬时快照
	ClientConnected prometheus.Gauge
	// ReqReceivedTotal 类型为 prometheus.Counter, Counter，就是一个计数器，可以累加，也可以减少
	ReqReceivedTotal prometheus.Counter
	// RspSendTotal 类型为 prometheus.Counter, Counter，就是一个计数器，可以累加，也可以减少
	RspSendTotal prometheus.Counter
)

func init() {

	ReqReceivedTotal = prometheus.NewCounter(prometheus.CounterOpts{
		Name: "tcp_server_request_received_total",
	})

	RspSendTotal = prometheus.NewCounter(prometheus.CounterOpts{
		Name: "tcp_server_response_send_total",
	})

	ClientConnected = prometheus.NewGauge(prometheus.GaugeOpts{
		Name: "tcp_server_client_connected",
	})

	prometheus.MustRegister(ReqReceivedTotal, RspSendTotal, ClientConnected)

	metricsServer := &http.Server{
		Addr: fmt.Sprintf(":%d", metricsHTTPPort),
	}

	mu := http.NewServeMux()

	mu.Handle("/metrics", promhttp.Handler())

	metricsServer.Handler = mu

	go func() {
		err := metricsServer.ListenAndServe()
		if err != nil {
			fmt.Println("prometheus-exporter http server start failed:", err)
		}
	}()
	fmt.Println("metrics server start ok(*:9999)")
}
